package com.nado.extensions.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nado.extensions.container.SpringBeanFactory;

/**
 * 객체 반환 시 Spring에서 먼저 해당 객체를 찾아보고 없으면 {@link ReflectionUtil}을 사용해서 생성한다.
 *
 */
@SuppressWarnings("unchecked")
public class SpringObjectFactory implements ObjectFactory {
	Log log = LogFactory.getLog(SpringObjectFactory.class);

	private static ObjectFactory objectFactory;

	private SpringObjectFactory() {}

	public static ObjectFactory getInstance() {
		if (objectFactory == null) {
			objectFactory = new SpringObjectFactory();
		}
		return objectFactory;
	}

	public <T> T getObject(String objectname) {
		try {
			return (T) SpringBeanFactory.getBean(objectname);
		} catch (Exception e) {
			log.debug("Cannot find bean-definition for '" + objectname
					+ "'. Trying to create Object via Reflection...");
		}
		return (T) ReflectionUtil.createInstance(objectname);
	}

	public <T> T getObject(String objectname, Object[] arguments) {
		try {
			return (T) SpringBeanFactory.getBean(objectname);
		} catch (Exception e) {
			log.debug("Cannot find bean-definition for '" + objectname
					+ "'. Trying to create Object via Reflection...");
		}
		return (T) ReflectionUtil.createInstance(objectname, arguments);
	}
}